using System;
using System.Runtime.CompilerServices;
using Nsb.Classes;
using jQueryApi;

namespace MinionsEdit.Classes
{
    [IgnoreNamespace]
    public static class MiUiOp
    {
        // ReSharper disable InconsistentNaming
        private static string _fromId;
        public static bool cancelled;
        private static jQueryEvent _e;
        private static jQueryUiObject _ui;
        private static bool _active;
        private static bool _queRestore;
        private static jQueryEventHandler _onAbort;

        private static string _snapshot;

        // ReSharper restore InconsistentNaming

        public static MinionEdit TheMinion
        {
            get { return MinionEdit.GetMinionById(_fromId); }
        }

        public static string Snapshot
        {
            get { return _snapshot; }
        }

        [AlternateSignature]
        public static extern void Init(MinionEdit mm, jQueryEvent e);

        public static void Init(MinionEdit mm, jQueryEvent e, jQueryUiObject ui)
        {
#if DEBUG
            if (_active)
            {
                Script.Literal("debugger");
            }
#endif
            _active = true;
            _queRestore = false;
            _onAbort = null;
            _e = e ?? null;
            _ui = ui ?? null;
            cancelled = false;
            _fromId = mm.Id;
            _snapshot = mm.SnapShot;
        }

        public static void SetCancel(jQueryEventHandler fn)
        {
            _onAbort = fn;
        }

        public static void Finish()
        {
            _active = false;
            if (_queRestore)
                Restore();
        }

        public static void Cancel()
        {
            cancelled = true;
        }

        public static void AbortEv(jQueryEvent e)
        {
            Inform.Debug("MiUiOp.Abort()");
            Cancel();
            if (_active)
                _queRestore = true;
            if (_onAbort != null)
            {
                _onAbort(e);
                _onAbort = null; // Only do this once
            }
        }

        public static void Restore()
        {
            TheMinion.RestoreFrom(_snapshot);
        }
    }
}